﻿using Furion.DependencyInjection;
using Furion.FriendlyException;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
using YFurion.Exceptions;

namespace UpperComputer.WPF.Entry.Handlers
{
    public class LogExceptionHandler : IExceptionHandler, ITransient
    {
        private readonly ILogger<LogExceptionHandler> _logger;
        public LogExceptionHandler(ILogger<LogExceptionHandler> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="exception">异常对象</param>
        /// <param name="infoName">信息名</param>
        /// <param name="feAction">友好异常处理委托</param>
        public void OnHandleException(Exception exception, string infoName, Action<AppFriendlyException> feAction = null)
        {
            try
            {
                if (exception is AppFriendlyException)
                {
                    AppFriendlyException fe = (AppFriendlyException)exception;
                    feAction(fe);
                }
                else
                {
                    _logger.LogError(exception, ExceptionToString(infoName));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ExceptionToString($"{infoName}处理函数"));
            }
        }

        /// <summary>
        /// 提取异常信息
        /// </summary>
        private string ExceptionToString(string info)
        {
            StringBuilder str = new StringBuilder($"{DateTime.Now}, {info}发生了一个错误！{Environment.NewLine}");
            return str.ToString();
        }
    }
}
